package logic

import (
	"context"
	"fmt"
	"math/rand"
	"shell/models/cache"
	"shell/models/mysql"

	"shell/houserpc/houserpc"
	"shell/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *houserpc.LoginRequest) (*houserpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User

	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Mobile).Result()
	if in.Mobile != "" {
		if result == "" {
			return nil, fmt.Errorf("短信验证码为空,请前去发送")
		}
		if result != in.SendSmsCode {
			return nil, fmt.Errorf("短信验证码错误,请重新输入")
		}
		mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
		if user.ID == 0 {
			user = mysql.User{
				Mobile:      in.Mobile,
				Password:    in.Password,
				Name:        fmt.Sprintf("用户昵称_%d", rand.Intn(100000)),
				HeaderImage: "https://cn.bing.com/images/search?q=%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F&FORM=IQFRBA&id=4AB9F18F65E479F3E1FAFBC116654EFB017DEA54",
			}
			mysql.DB.Debug().Create(&user)
		} else {
			if in.Password != user.Password {
				return nil, fmt.Errorf("密码错误,请重新输入")
			}
		}
	}

	return &houserpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
